package chen.web.controller.blog;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import chen.web.controller.blog.form.LoginForm;
import chen.web.controller.forum.JSONError;
import chen.web.controller.forum.JSONResponse;
import chen.web.user.Account;
import chen.web.user.AccountManager;
import chen.web.user.SessionSupport;

@Controller
public class LoginAndLogout {
	
	private @Autowired Validator validator;
	private @Autowired AccountManager am;
	private @Autowired SessionSupport ss;
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public @ResponseBody JSONResponse login(@RequestBody LoginForm  bean, HttpServletResponse response){
		Set<ConstraintViolation<LoginForm>> failures = validator.validate(bean);
		if (!failures.isEmpty()) {
			return JSONResponse.invalid(failures);
		} 
		
		Account account = am.getAccountByName(bean.getNickname());
		if(account == null || !account.getPassword().check(bean.getPassword())){
			return JSONResponse.error(JSONError.create("nickname", "邮箱或密码有误"));
		}
		
		if(bean.isRemember()){
			ss.createPersistentSession(response, account);
		}else {
			ss.createSession(response, account);
		}
		return JSONResponse.successed();
	}
	
	@RequestMapping(value="/logout", method=RequestMethod.GET)
	public @ResponseBody JSONResponse logout(HttpServletRequest request, HttpServletResponse response){
		ss.terminateSession(request, response);
		return JSONResponse.successed();
	}
	
	@RequestMapping(value="/login", method=RequestMethod.GET)
	public String login(){
		return "login";
	}

}
